package com.bottomlord.inject;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Set;

import static com.bottomlord.functions.ThrowableAction.execute;

/**
 * @author ChenYue
 * @date 2021/4/8 11:25
 */
public class JndiComponentRepository extends AbstractComponentRepository {
    private static final String COMPONENT_ENV_CONTEXT_NAME = "java:comp/env";
    private Context envContext;

    @Override
    protected Object doGetComponent(String componentName) {
        return null;
    }

    @Override
    protected Set<String> listComponentNames() {
        return null;
    }

    public void initEnvContext() {
        if (this.envContext != null) {
            return;
        }

        Context context = null;
        try {
            context = new InitialContext();
            this.envContext = (Context) context.lookup(COMPONENT_ENV_CONTEXT_NAME);
        } catch (NamingException e) {
            throw new RuntimeException(e);
        } finally {
            close(context);
        }
    }

    private static void close(Context context) {
        if (context != null) {
            execute(context::close);
        }
    }
}
